package redisson.lock;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class TestLock implements SmartInitializingSingleton {

	@Autowired
	RedissonClient redissonClient;

	@Override
	public void afterSingletonsInstantiated() {

		RLock lock = redissonClient.getLock("test:lock:11");

		try {
			boolean tryLock = lock.tryLock(0, 3, TimeUnit.MINUTES);
			if (tryLock) {
				log.info("### 获取锁成功,3分钟后自己释放");
			} else {
				log.info("### 获取锁失败");
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			if (lock.isHeldByCurrentThread())
				log.info("### 是当前线程获取锁,未主动释放,3分钟后自己释放");
//				lock.unlock();
		}

	}

}
